import Core from '../core'

function Manager() {
  // 页面可以嵌入多个ocx控件
  // 格式: {}
  this.ctrls = {}
  // 当前使用的控件id
  this.id = ''
}

Manager.prototype.Registry = function({ id, parent }) {
  if (this.ctrls.hasOwnProperty(id)) {
    // 释放内存
    this.ctrls[id].release()
    delete this.ctrls[id]
  }
  // 注册到仓库中
  const core = new Core({ parent })
  this.ctrls[id] = core
  // console.log('注册:', id, this.ctrls)
}

Manager.prototype.UnRegistry = function(id) {
  if (this.ctrls.hasOwnProperty(id)) {
    const core = this.ctrls[id]
    // 释放内存
    core.release()
    delete this.ctrls[id]
  }
}

// 切换ocx
Manager.prototype.MakeCurrent = function(id) {
  if (this.ctrls.hasOwnProperty(id)) {
    this.id = id
    return true
  } else {
    return false
  }
}

Manager.prototype.GetCore = function(id) {
  return this.ctrls[id] || null
}

Manager.prototype.GetDiagram = function(id) {
  const core = this.GetCore(id)
  if (core === null) {
    return null
  } else {
    return core.GetDiagram()
  }
}

Manager.prototype.CurId = function() {
  return this.id
}

Manager.prototype.CurCore = function() {
  return this.GetCore(this.id)
}

Manager.prototype.CurDiagram = function() {
  return this.GetDiagram(this.id)
}

// 释放内存
Manager.prototype.release = function() {
  for (const id in this.ctrls) {
    this.ctrls[id].release()
    delete this.ctrls[id]
  }
}

// 定义全局变量并导出
const globalManager = new Manager()

export default globalManager
